//
//  SEGOpenDoorBussinessManager.m
//  SEGUhomeIntelligentHardware
//
//  Created by Clavis on 2018/12/5.
//  Copyright © 2018 刘山. All rights reserved.
//

// Helper
#import "SEGOpenDoorBussinessManager.h"
// View
#import "SEGOpenDoorAlertView.h"
#import "SEGDoorQRCodeView.h"
#import "SEGDoorRollingGateView.h"
// Model
#import <SEGModel/SEGNewMyDoorListModel.h>
#import <SEGModel/SEGNewOpenDoorModel.h>
#import "SoundService.h"
// ViewModel
#import <SEGViewModel/SEGOpenDoorViewModel.h>
// Other
#import <ReactiveObjC/ReactiveObjC.h>
#import <CoreBluetooth/CoreBluetooth.h>

static SEGOpenDoorBussinessManager * bussinessInstance = nil;

@interface SEGOpenDoorBussinessManager ()

@property (nonatomic, copy) void (^openDoorSuccessCallback)(SEGNewOpenDoorModel *);
@property (nonatomic, copy) void (^openDoorFailCallback)(SEGNewOpenDoorModel *);
@property (nonatomic, strong) SEGDoorQRCodeView *qrcodeView;
@property (nonatomic, strong) SEGDoorRollingGateView *rollingGateView;
@property (nonatomic, strong) SEGOpenDoorViewModel *openDoorViewModel;

@end

@implementation SEGOpenDoorBussinessManager

+ (instancetype)shareInstance {
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        bussinessInstance = [[super allocWithZone:NULL] init] ;
    }) ;

    return bussinessInstance ;
}

+ (id)allocWithZone:(struct _NSZone *)zone {
    return [SEGOpenDoorBussinessManager shareInstance] ;
}

- (id)copyWithZone:(struct _NSZone *)zone {
    return [SEGOpenDoorBussinessManager shareInstance] ;
}

/**
 开门
 
 @param doorModel 门禁模型
 @param completeCallback 开门成功回调
 @param openDoorFailCallback 开门失败回调
 */
- (void)openDoorWithDoorModel:(SEGNewMyDoorListModel *)doorModel openDoorSuccessCallback:(void(^)(SEGNewOpenDoorModel* data))completeCallback openDoorFailCallback:(void(^)(SEGNewOpenDoorModel* data))openDoorFailCallback {
    self.openDoorFailCallback = openDoorFailCallback;
    [self openDoorWithDoorModel:doorModel completeCallback:completeCallback];
}

/**
 开门
 
 @param doorModel 门禁模型
 @param completeCallback 开门成功回调
 */
- (void)openDoorWithDoorModel:(SEGNewMyDoorListModel *)doorModel completeCallback:(void(^)(SEGNewOpenDoorModel* data))completeCallback {
    self.openDoorSuccessCallback = completeCallback;
    
    @weakify(self);
    [[self.openDoorViewModel openDoorSignal:doorModel] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        
        RACTupleUnpack(NSNumber *statusObj, id tip) = x;
        SEGOpenDoorStatus status = statusObj.intValue;
        switch (status) {
            case SEGOpenDoorStatus_Begin:
                [SVProgressHUD showWithStatus:kOpenDoorMessage_Opening];
                [[SoundService sharedSoundService] clickDoorOpen];
                break;
            case SEGOpenDoorStatus_ShowQRCode:
            {
                [SVProgressHUD dismiss];
                [self showQRCodeView:doorModel qrString:ValueToString(tip) completeCallback:completeCallback];
                break;
            }
            case SEGOpenDoorStatus_ShowRollingGate:{
                [SVProgressHUD dismiss];
                [self showRollingGateView:doorModel];
                break;
            }
            case SEGOpenDoorStatus_Success:
            {
                [SVProgressHUD dismiss];
                [[SoundService sharedSoundService] doorOpenMsg];
                [SEGAlertView showTmepMessageWithMessage:kOpenDoorMessage_Success withtime:0.1];
                if (self.openSuccessBlock) {
                    self.openSuccessBlock();
                }
                if (self.openDoorSuccessCallback) {
                    SEGNewOpenDoorModel *openDoorModel = [SEGNewOpenDoorModel new];
                    openDoorModel.type = @"AFTERFDOOROPEN";
                    openDoorModel.data = doorModel;
                    openDoorModel.doorStatus = SEGOpenDoorStatus_Success;
                    self.openDoorSuccessCallback(openDoorModel);
                }
                break;
            }
            default:
                break;
        }
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        if (error.code == SEGOpenDoorErrorType_NoBluetoothAuthority) {
            CBPeripheralManagerState bluetoothState = [error.userInfo[SEGOpenDoorFailBluetoothStateKey] integerValue];
            [SEGOpenDoorBussinessManager showOpenBluetoothAlterWithBluetoothState:bluetoothState];
            return;
        }
        if (error.code == SEGOpenDoorErrorType_OpenBluetoothDoorFail || error.code == SEGOpenDoorErrorType_NetworkDoorFail) {
            if (self.openDoorFailCallback) {
                SEGNewOpenDoorModel *model = [SEGNewOpenDoorModel new];
                model.data = doorModel;
                model.doorStatus = SEGOpenDoorStatus_Failed;
                self.openDoorFailCallback(model);
            }
        }
        
        NSString *errorTipTitle = error.userInfo[SEGOpenDoorErrorTipTitleKey];
        if (errorTipTitle.length > 0) {
            SEGOpenDoorAlertView *alertView = [[SEGOpenDoorAlertView alloc] init];
            [alertView showWithTitle:errorTipTitle text:error.localizedDescription];
        } else {
            [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
        }
    }];
}

/// 显示门禁二维码
/// @param doorModel doorModel
/// @param qrString qrString
/// @param completeCallback completeCallback
- (void)showQRCodeView:(SEGNewMyDoorListModel *)doorModel qrString:(NSString *)qrString completeCallback:(void(^)(SEGNewOpenDoorModel* data))completeCallback {
    if (!self.qrcodeView) {
        SEGDoorQRCodeView *qrCodeView = [[SEGDoorQRCodeView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight())];
        self.qrcodeView = qrCodeView;
    }
    self.qrcodeView.frame = CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight());
    self.qrcodeView.hidden = NO;
    [self.qrcodeView createQRCodeWithString:qrString doorName:doorModel.name needRefresh:YES];
    WeakSelf;
    self.qrcodeView.refreshBlock = ^{
        // 重新请求开门
        [weakSelf openDoorWithDoorModel:doorModel completeCallback:completeCallback];
    };
    [[UIApplication sharedApplication].keyWindow addSubview:self.qrcodeView];
}

/// 显示卷闸门视图
/// @param doorModel doorModel
- (void)showRollingGateView:(SEGNewMyDoorListModel *)doorModel {
    if (!self.rollingGateView) {
        self.rollingGateView = [[SEGDoorRollingGateView alloc] init];
    }
    self.rollingGateView.frame = [UIScreen mainScreen].bounds;
    self.rollingGateView.hidden = NO;
    WeakSelf;
    self.rollingGateView.buttonClickBlock = ^(NSInteger index) {
        [SVProgressHUD show];
        [[weakSelf.openDoorViewModel openRollingGateDoorSignal:doorModel actionType:index] subscribeNext:^(id  _Nullable x) {
            [SVProgressHUD dismiss];
            [SEGAlertView showTmepMessageWithMessage:ValueToString(x)];
            [weakSelf.rollingGateView removeFromSuperview];
        } error:^(NSError * _Nullable error) {
            [SVProgressHUD dismiss];
            [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
            [weakSelf.rollingGateView removeFromSuperview];
        }];
    };
    [[UIApplication sharedApplication].keyWindow addSubview:self.rollingGateView];
}

/// 显示打开蓝牙的提示
/// @param state 当前蓝牙状态
+ (void)showOpenBluetoothAlterWithBluetoothState:(CBPeripheralManagerState)state {
    // 蓝牙开启状态 无需处理
    if (state == CBPeripheralManagerStatePoweredOn) return;

// iOS13及以上, 需要区分蓝牙状态, 未认证跳转应用设置, 未开启弹窗提示
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
    if (state == CBPeripheralManagerStateUnauthorized) {
        NSString *title = [NSString stringWithFormat:@"打开蓝牙来允许“%@”连接到配件",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]];
        UIAlertController* alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* confirmAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction* _Nonnull action) {
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        }];
        [alertController addAction:confirmAction];
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction* _Nonnull action) {
        }];
        [alertController addAction:cancelAction];
        UIViewController *currentVC = [[SEGUhomeMediator sharedInstance] seg_getCurrentController:nil];
        [currentVC presentViewController:alertController animated:YES completion:nil];

        return;
    }
#endif

    if (state == CBPeripheralManagerStateUnknown ||
        state == CBPeripheralManagerStateUnauthorized ||
        state == CBPeripheralManagerStatePoweredOff) {
        NSString *title = @"无法获取您的蓝牙信息";
        NSString *message = [NSString stringWithFormat:@"请到手机系统【设置】中打开蓝牙，并允许“%@”使用蓝牙权限。",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]];
        UIAlertController* alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction* _Nonnull action) {
        }];
        [alertController addAction:cancelAction];
        UIViewController *currentVC = [[SEGUhomeMediator sharedInstance] seg_getCurrentController:nil];
        [currentVC presentViewController:alertController animated:YES completion:nil];
    } else {
        [SEGAlertView showTmepMessageWithMessage:@"蓝牙异常"];
    }
}

#pragma mark - Getter & Setter
- (SEGOpenDoorViewModel *)openDoorViewModel {
    if (!_openDoorViewModel) {
        _openDoorViewModel = [[SEGOpenDoorViewModel alloc] init];
    }
    return _openDoorViewModel;
}

@end
